/*
 * Module name : CatalogTreeItemView
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import RadioWidget from '../../widgets/RadioWidget.js';
import CheckboxWidget from '../../widgets/CheckboxWidget.js';
import InputWidget from '../../widgets/InputWidget.js';
import {
    getOpt
} from "../../tools.js";

const template = require('./templates/CatalogTreeItemView.mustache');

const CatalogTreeItemView = Mn.View.extend({
    tagName: 'tr',
    template: template,
    regions: {
        td_action: 'td.action',
        td_input: 'td.input'
    },
    modelEvents: {
        'change:selected': 'render',
        'change:quantity': 'render',
    },
    // Listen to child view events
    childViewEvents: {
        'finish': "onChange",
    },
    // Bubble up child view events
    childViewTriggers: {},
    initialize(options) {
        if (getOpt(this, 'selected', false)) {
            this.model.set('selected');
        }
        this.config = Radio.channel('config')
        this.compute_mode = this.config.request('get:options', "compute_mode");
        this.decimal_to_display = this.config.request('get:options', "decimal_to_display");
        this.multiple = getOpt(this, 'multiple', false);
    },
    onRender() {
        let widget;
        let options = {
            field_name: 'check',
            ariaLabel: 'Sélectionner ce produit',
            toggle: false
        };
        if (this.multiple) {
            options = Object.assign(
                options, {
                    value: this.model.get('selected'),
                    true_val: true,
                    false_val: false,
                }
            );
            widget = new CheckboxWidget(options);
        } else {
            options['value'] = true;
            widget = new RadioWidget(options);
        }
        this.showChildView('td_action', widget);
        this.showChildView(
            'td_input',
            new InputWidget({
                field_name: 'quantity',
                ariaLabel: 'qte',
                title: "",
                value: this.model.get('quantity'),
                required: true,
                pattern: "\-?[0-9]*([,.][0-9]{0,5})?"
            })
        );
    },
    onChange(field_name, value) {
        if (field_name == 'check')
            this.model.collection.setSelected(this.model, value);
        if (field_name == 'quantity')
            this.model.collection.setQuantity(this.model, value);
    },
    templateContext() {
        let amount_label;
        if (this.compute_mode == 'ht') {
            amount_label = this.model.ht_label(this.decimal_to_display);
        } else {
            amount_label = this.model.ttc_label(this.decimal_to_display);
        }
        let quantity = this.model.get('quantity');
        return {
            amount_label: amount_label,
            quantity: quantity,
        };
    }
});
export default CatalogTreeItemView
